<?php
namespace app\index\controller;
use think\Controller;
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
class Login extends Controller
{
    // 登录接口
    public function index()
    {
        $data = input();//username password
        if (empty($data['username'])) {
            apiReturn(201,'用户名不能为空');
        }
        if (empty($data['password'])) {
            apiReturn(202,'密码不能为空');
        }
        $manage = model('CrmManage');
        $oneManage = $manage->getManageInfo('',$data['username']);
        if (!empty($oneManage)) {
            $userpass = password($data['password']);//加密函数
            if ($oneManage['password'] == $userpass) {
                if ($oneManage['status'] == 0) {
                    apiReturn(205,'账号已禁用');
                }
                $ip = request()->ip();
                $mac = clientMac();
                if (!empty($oneManage['allow_ip']) && ($oneManage['allow_ip'] != $ip)) {
                    apiReturn(206,'IP地址错误');
                }
                if (!empty($oneManage['allow_mac']) && ($oneManage['allow_mac'] != $mac)) {
                    apiReturn(207,'Mac地址错误');
                }
                $ipArea = ipArea($ip);

                //添加登录日志
                $login_datas = array(
                    'manage_id'=>$oneManage['id'],
                    'username'=>$oneManage['username'],
                    'manage_name'=>$oneManage['name'],
                    'ip'=>$ip,
                    'ip_area'=>$ipArea['country'].'-'.$ipArea['area'],
                    'mac'=>$mac,
                    'date'=>time()
                );
                db('crm_manage_login')->insert($login_datas);

                //更新token
                // $mange_datas['token'] = password($oneManage['id'].time());
                $mange_datas['token'] = password($oneManage['id']."111");
                db('crm_manage')->where('id',$oneManage['id'])->update($mange_datas);
                apiReturn(200,'登录成功',$mange_datas['token']);
            }else{
                apiReturn(204,'用户名或密码不正确');
            }
        }else{
            apiReturn(203,'用户名或密码不正确');
        }
    }

}
